import * as DT from 'dt-sdk'
import moment from 'moment'
import { mapMutations, mapGetters } from 'vuex'
import Controls from './controls/index.vue'
import Toolbar from './toolbar/index.vue'
export let viewer = null
export let lodLayer = new DT.LODSceneLayer()
export default {
  name: 'DtScene',
  components: { Controls, Toolbar },
  provide() {
    return {
      sceneStatus: this.sceneStatus,
      changeTime: this.changeTime,
      // requestMode: this.requestMode
    }
  },
  props: {
    sceneTime: {
      type: Object,
      default:() => {
        return {}
      }
    },
    showAlarmTool: {
      type: Boolean,
      default: false
    }
    // requestMode: {
    //   type: String,
    //   default: 'async',
    //   validator: (val) => ['realtime', 'async'].includes(val)
    // }
  },
  data() {
    return {
      sceneStatus: {
        isInited: false,
      },
      mode: true,
      // sceneMode
    }
  },
  computed: {
    ...mapGetters(['sceneMode']),
  },
  watch: {
    /**
     * 监听场景模式变化
     * @author Farley
     * @date 2021-12-23
     * @param {any} val
     * @returns {any}
     */
    sceneMode: {
      handler: function (nv, ov) {
        this.mode = nv
      },
      immediate: true

    }
  },
  created() { },
  mounted() {
    this.initScene()
  },
  beforeDestroy() {
    if (viewer) {
      viewer.destroy();
      viewer = null
      lodLayer = new DT.LODSceneLayer()
      this.isInited = false
    }
  },
  methods: {
    ...mapMutations('app', ['SET_CURRENT_TIME', 'SET_SCENE_MODE']),
    /**
     * 向外暴露时间变化事件
     * @author Farley
     * @date 2021-11-19
     * @param {any} time
     * @returns {any}
     */
    changeTime(time, speed) {
      this.$emit('change-time', moment(time).utc().format('YYYY-MM-DDTHH:mm:ss') + 'Z', speed)
    },
    /**
     * 更新场景模式到 store
     * @author Farley
     * @date 2021-11-17
     * @param {any} val
     * @returns {any}
     */
    changeMode(val) {
      this.SET_SCENE_MODE(val)
    },
    /**
     * 初始化场景
     * @author Farley
     * @date 2021-10-25
     * @returns {any}
     */
    initScene() {
      // let tilingScheme, url, urlMap;
      // tilingScheme = new DT.Cesium.GeographicTilingScheme()
      //   url = 'static/wxmaps/{z}/{x}/{y}.jpg'
      //   // url = 'static/wxmaps/{z}/{x}/{y}.jpg'
      //   console.log(url)
      //   urlMap = new DT.Cesium.UrlTemplateImageryProvider({
      //     url,
      //     tilingScheme: tilingScheme,
      //     minimumLevel: 2
      //   })
      // 开发环境下访问内网地图影像
      // if (process.env.NODE_ENV === "development") {
      //   console.log('当前为开发环境，访问内网地图影像')
      //   tilingScheme = new DT.Cesium.GeographicTilingScheme()
      //   url = 'static/wxmaps/{z}/{x}/{y}.jpg'
      //   // url = 'static/wxmaps/{z}/{x}/{y}.jpg'
      //   console.log(url)
      //   urlMap = new DT.Cesium.UrlTemplateImageryProvider({
      //     url,
      //     tilingScheme: tilingScheme,
      //     minimumLevel: 2
      //   })
      // } else {
      //   // 生产环境下
      //   if (window.ipConfig.map && window.ipConfig.map !== '') {
      //     console.log('当前为生产环境，且通过 config.js 配置地图影像地址，访问指定地图影像')
      //     console.log(window.ipConfig.map + '/{newZ}/{x}/{newY}.jpg')
      //     // 如果有通过 config.js -> ipConfig.map 配置地图影像地址
      //     tilingScheme = new DT.Cesium.GeographicTilingScheme()
      //     urlMap = new DT.Cesium.UrlTemplateImageryProvider({
      //       url: window.ipConfig.map + '/{newZ}/{x}/{newY}.png',
      //       tilingScheme: tilingScheme,
      //       customTags: {
      //         newZ: function (imageryProvider, x, y, level) {
      //           return level + 1;
      //         },
      //         newY: function (imageryProvider, x, y, level) {
      //           return (
      //             imageryProvider.tilingScheme.getNumberOfYTilesAtLevel(level) -
      //             y -
      //             1
      //           );
      //         },
      //       },
      //       minimumLevel: 2
      //     })
      //   } else {
      //     console.log('当前为生产环境，访问工程 public 下地图影像')
      //     // 没有则访问工程 public 下地图影像
      //     tilingScheme = new DT.Cesium.WebMercatorTilingScheme()
      //     url = process.env.BASE_URL + 'wxmaps/{z}/{x}/{y}.jpg'
      //     console.log(url)
      //     urlMap = new DT.Cesium.UrlTemplateImageryProvider({
      //       url,
      //       tilingScheme: tilingScheme,
      //       minimumLevel: 2
      //     })
      //   }
      // }


      const urlMap = new DT.Cesium.UrlTemplateImageryProvider({
        // url: 'http://192.168.1.10:7412/{z}/{x}/{y}.jpg',
        url: process.env.BASE_URL + 'wxmaps/{z}/{x}/{y}.jpg',
        tilingScheme: new DT.Cesium.WebMercatorTilingScheme(),
        minimumLevel: 2
      })
      viewer = new DT.Viewer('viewer-container', {
        // imageryProvider: new DT.Cesium.TileMapServiceImageryProvider({
        //   url: DT.Cesium.buildModuleUrl('Assets/Textures/NaturalEarthII')
        // }),
        imageryProvider: urlMap,
        // terrainProvider: new DT.Cesium.CesiumTerrainProvider({
        //   url: 'http://192.168.1.10:7413/'
        // }),
        // mapMode2D: DT.Cesium.MapMode2D.ROTATE
        // animation: true,//动画器件，显示当前时间，允许跳转特定时间
	      // timeline: true,//时间轴
        
        skyBox: new DT.Cesium.SkyBox({
          sources: {
            positiveX: process.env.BASE_URL + 'static/sky-box/tycho2t3_80_px.jpg',
            negativeX: process.env.BASE_URL + 'static/sky-box/tycho2t3_80_mx.jpg',
            positiveY: process.env.BASE_URL + 'static/sky-box/tycho2t3_80_py.jpg',
            negativeY: process.env.BASE_URL + 'static/sky-box/tycho2t3_80_my.jpg',
            positiveZ: process.env.BASE_URL + 'static/sky-box/tycho2t3_80_pz.jpg',
            negativeZ: process.env.BASE_URL + 'static/sky-box/tycho2t3_80_mz.jpg'
          }
        }),
        "contextOptions": {
          "webgl": {
            "alpha": true,
            "depth": false,
            "stencil": true,
            "antialias": true,
            "premultipliedAlpha": true,
            "preserveDrawingBuffer": true,
            "failIfMajorPerformanceCaveat": true
          },
          "allowTextureFilterAnisotropic": true
        },
        mapMode2D: DT.Cesium.MapMode2D.ROTATE,
      })
      // viewer.sceneMode = DT.Cesium.SceneMode.SCENE2D
      window.viewer = viewer
      // 设置是否已初始化场景
      this.sceneStatus.isInited = true
     
      // if (process.env.NODE_ENV === 'development') {
      viewer.cesiumViewer.scene.debugShowFramesPerSecond = false;
      
      // viewer.cesiumViewer.scene.globe.depthTestAgainstTerrain = true
      // }
      viewer.cesiumViewer.scene.globe.depthTestAgainstTerrain = false;
      viewer.cesiumViewer.scene.screenSpaceCameraController.maximumZoomDistance = 500000000;
      viewer.cesiumViewer.camera.setView({
        // fromDegrees()方法，将经纬度和高程转换为世界坐标
        destination:DT.Cesium.Cartesian3.fromDegrees(115.7, 39.4, 20000000.0),
          orientation:{
            heading: 6.283185307179586,
            // 视角
            pitch: -1.5686521559334161,
            roll: 0,
          }
        });
      viewer.addLayer(lodLayer)
      // 去掉版权
      document.querySelector('.cesium-widget-credits').style.display = 'none'

      let leftDoubleClickHandler = new DT.Cesium.ScreenSpaceEventHandler(viewer.cesiumViewer.scene.canvas)
      // 双击锁定卫星视角
      leftDoubleClickHandler.setInputAction(({ position }) => {
        let pick = viewer.cesiumViewer.scene.pick(position)
        if (pick && pick.primitive && pick.primitive.entityId) {
          let entity = lodLayer.getEntityById(pick.primitive.entityId)
          viewer.track(entity)
        } else {
          viewer.untrack()
        }
      }, DT.Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK)
    },
  }
}